package pl.iachoo.ctl.tabory.ui.editors.vagons.composites;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.SectionPart;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;

import pl.iachoo.ctl.tabory.dao.hibernate.interfaces.IVagonService;
import pl.iachoo.ctl.tabory.dao.hibernate.services.ServiceManager;
import pl.iachoo.ctl.tabory.dao.hibernate.vo.CompositionVO;
import pl.iachoo.ctl.tabory.dao.hibernate.vo.VagonVO;
import pl.iachoo.ctl.tabory.ui.editors.vagons.VagonSelection;
import pl.iachoo.ctl.tabory.ui.properties.Messages;
import pl.iachoo.ctl.tabory.ui.selection.ISelectionListener;
import pl.iachoo.ctl.tabory.ui.selection.ISelectionProvider;
import pl.iachoo.ctl.tabory.ui.utils.CommonDateUtils;

public class VagonDetailSectionPart extends SectionPart implements
		ISelectionProvider<VagonSelection> {

	private final static Logger log = Logger
			.getLogger(VagonDetailSectionPart.class);

	private ISelectionListener<VagonSelection> selectionListener;

	private VagonSelection selection;
	private Text vagonNameText;
	private DateTime revisionOneStartDate;
	private DateTime revisionOneEndDate;
	private DateTime revisionTwoStartDate;
	private DateTime revisionTwoEndDate;
	private Text revisionDistanceTxt;
	private Text revisionCorrectionTxt;
	private Combo compositionCombo;
	private Button isActiveChbtn;
	private Composite composite;
	private Button saveButton;
	private Button cancelButton;

	/**
	 * Create the SectionPart.
	 * 
	 * @param parent
	 * @param toolkit
	 * @param style
	 */
	public VagonDetailSectionPart(Composite parent, FormToolkit toolkit,
			int style) {
		super(parent, toolkit, style);
		createClient(getSection(), toolkit);
		initActinos();
	}

	/**
	 * Fill the section.
	 */
	private void createClient(Section section, FormToolkit toolkit) {
		section.setText(Messages.getString("vagons.editor.details"));
		Composite container = toolkit.createComposite(section);

		section.setClient(container);
		container.setLayout(new GridLayout(2, false));

		Label label_4 = toolkit.createLabel(container, "Nazwa wagonu:",
				SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		vagonNameText = new Text(container, SWT.BORDER);
		vagonNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));

		Label label = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2,
				1));
		toolkit.adapt(label, true, true);

		Label label_5 = toolkit.createLabel(container,
				"Rewizja cykliczna (pocz\u0105tek):", SWT.NONE);
		label_5.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		revisionOneStartDate = new DateTime(container, SWT.BORDER);
		toolkit.adapt(revisionOneStartDate);
		toolkit.paintBordersFor(revisionOneStartDate);

		Label label_6 = toolkit.createLabel(container,
				"Rewizja cykliczna (koniec):", SWT.NONE);
		label_6.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		revisionOneEndDate = new DateTime(container, SWT.BORDER);
		toolkit.adapt(revisionOneEndDate);
		toolkit.paintBordersFor(revisionOneEndDate);

		Label label_7 = toolkit.createLabel(container,
				"Rewizja okresowa (pocz\u0105tek):", SWT.NONE);
		label_7.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		revisionTwoStartDate = new DateTime(container, SWT.BORDER);
		toolkit.adapt(revisionTwoStartDate);
		toolkit.paintBordersFor(revisionTwoStartDate);

		Label label_8 = toolkit.createLabel(container,
				"Rewizja okresowa (koniec):", SWT.NONE);
		label_8.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		revisionTwoEndDate = new DateTime(container, SWT.BORDER);
		toolkit.adapt(revisionTwoEndDate);
		toolkit.paintBordersFor(revisionTwoEndDate);

		Label label_1 = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				2, 1));
		toolkit.adapt(label_1, true, true);

		Label label_9 = toolkit.createLabel(container, "Dystans rewizyjny:",
				SWT.NONE);
		label_9.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		revisionDistanceTxt = new Text(container, SWT.BORDER);
		revisionDistanceTxt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				false, false, 1, 1));

		Label label_10 = toolkit.createLabel(container, "Korekta dystansu:",
				SWT.NONE);
		label_10.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		revisionCorrectionTxt = new Text(container, SWT.BORDER);
		revisionCorrectionTxt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				false, false, 1, 1));

		Label label_2 = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				2, 1));
		toolkit.adapt(label_2, true, true);

		Label label_11 = toolkit
				.createLabel(container, "Sk\u0142ad:", SWT.NONE);
		label_11.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		compositionCombo = new Combo(container, SWT.NONE);
		compositionCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				false, false, 1, 1));
		toolkit.adapt(compositionCombo);
		toolkit.paintBordersFor(compositionCombo);

		Label label_3 = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				2, 1));
		toolkit.adapt(label_3, true, true);

		isActiveChbtn = toolkit.createButton(container, "Aktywny", SWT.CHECK);
		isActiveChbtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false,
				false, 1, 1));
		new Label(container, SWT.NONE);

		composite = toolkit.createComposite(container, SWT.NONE);
		composite.setLayout(new GridLayout(3, false));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false,
				2, 1));
		toolkit.paintBordersFor(composite);

		Label lblL = toolkit.createLabel(composite, "", SWT.NONE);
		lblL.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
		composite.setVisible(false);

		saveButton = toolkit.createButton(composite, "zapisz", SWT.FLAT);
		saveButton.setToolTipText("zapisz");
		saveButton.setImage(PlatformUI.getWorkbench().getSharedImages()
				.getImage(ISharedImages.IMG_ETOOL_SAVE_EDIT));
		saveButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));

		cancelButton = toolkit.createButton(composite, "anuluj", SWT.FLAT);
		cancelButton.setToolTipText("anuluj");
		cancelButton.setImage(PlatformUI.getWorkbench().getSharedImages()
				.getImage(ISharedImages.IMG_TOOL_UNDO));
		cancelButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
	}

	private void initActinos() {
		saveButton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked")
			@Override
			public void widgetSelected(SelectionEvent e) {
				VagonVO selectedVagon = selection.getSelectedVagon();
				String internalId = vagonNameText.getText();
				double revisionCorrection = Double
						.parseDouble(revisionCorrectionTxt.getText());
				double revisionDistance = Double
						.parseDouble(revisionDistanceTxt.getText());
				Date revisionOneStart = CommonDateUtils.getDate(
						revisionOneStartDate.getYear(),
						revisionOneStartDate.getMonth(),
						revisionOneStartDate.getDay());
				Date revisionOneEnd = CommonDateUtils.getDate(
						revisionOneEndDate.getYear(),
						revisionOneEndDate.getMonth(),
						revisionOneEndDate.getDay());
				Date revisionTwoStart = CommonDateUtils.getDate(
						revisionTwoStartDate.getYear(),
						revisionTwoStartDate.getMonth(),
						revisionTwoStartDate.getDay());
				Date revisionTwoEnd = CommonDateUtils.getDate(
						revisionTwoEndDate.getYear(),
						revisionTwoEndDate.getMonth(),
						revisionTwoEndDate.getDay());
				List<CompositionVO> listComposition = (List<CompositionVO>) compositionCombo
						.getData();
				CompositionVO composition = null;
				if (listComposition != null) {
					if (compositionCombo.getSelectionIndex() != -1) {
						composition = listComposition.get(compositionCombo
								.getSelectionIndex());
					}
				}
				boolean isActive = isActiveChbtn.getSelection();
				selectedVagon.setActive(isActive);
				selectedVagon.setCompositionVO(composition);
				selectedVagon.setInternalId(internalId);
				selectedVagon.setRevisionCorrection(revisionCorrection);
				selectedVagon.setRevisionDistance(revisionDistance);
				selectedVagon.setRevOneFrom(revisionOneStart);
				selectedVagon.setRevOneTo(revisionOneEnd);
				selectedVagon.setRevTwoFrom(revisionTwoStart);
				selectedVagon.setRevTwoTo(revisionTwoEnd);
				selectedVagon.setDeleted(false);
				try {
					IVagonService vagonService = ServiceManager
							.getVagonService();
					vagonService.addVagon(selectedVagon);
					selection.setSelectedVagon(selectedVagon);
					List<VagonVO> listVagons = selection.getListVagons();
					if (listVagons == null) {
						listVagons = new ArrayList<VagonVO>();
					}
					selection.setListVagons(listVagons);
					listVagons.add(selectedVagon);
					selection.setEditing(false);
					selectionListener.selectionChanged(selection);
				} catch (Exception ex) {
					selection.setEditing(false);
					selection.setSelectedVagon(null);
					selectionListener.selectionChanged(selection);
					log.error(ex.getMessage(), ex);
				}
				selection.setSelectedVagon(selectedVagon);
			}
		});

		cancelButton.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				selection.setEditing(false);
				selection.setSelectedVagon(null);
				selectionListener.selectionChanged(selection);
			}

		});
	}

	@Override
	public VagonSelection getSelection() {
		return selection;
	}

	@Override
	public void setSelection(VagonSelection selection) {
		this.selection = selection;
		VagonVO selectedVagon = selection.getSelectedVagon();
		if (selectedVagon != null) {
			String internalId = selectedVagon.getInternalId();
			CompositionVO compositionVO = selectedVagon.getCompositionVO();
			Double revisionCorrection = selectedVagon.getRevisionCorrection();
			Double revisionDistance = selectedVagon.getRevisionDistance();
			Date revOneFrom = selectedVagon.getRevOneFrom();
			Date revOneTo = selectedVagon.getRevOneTo();
			Date revTwoFrom = selectedVagon.getRevTwoFrom();
			Date revTwoTo = selectedVagon.getRevTwoTo();
			boolean active = selectedVagon.isActive() == null ? false
					: selectedVagon.isActive();
			vagonNameText.setText(String.valueOf(internalId));
			revisionCorrectionTxt.setText(String.valueOf(revisionCorrection));
			revisionDistanceTxt.setText(String.valueOf(revisionDistance));
			revisionOneStartDate.setDate(CommonDateUtils.getYear(revOneFrom),
					CommonDateUtils.getMonth(revOneFrom),
					CommonDateUtils.getDay(revOneFrom));
			revisionOneEndDate.setDate(CommonDateUtils.getYear(revOneTo),
					CommonDateUtils.getMonth(revOneTo),
					CommonDateUtils.getDay(revOneTo));
			revisionTwoStartDate.setDate(CommonDateUtils.getYear(revTwoFrom),
					CommonDateUtils.getMonth(revTwoFrom),
					CommonDateUtils.getDay(revTwoFrom));
			revisionTwoEndDate.setDate(CommonDateUtils.getYear(revTwoTo),
					CommonDateUtils.getMonth(revTwoTo),
					CommonDateUtils.getDay(revTwoTo));
			isActiveChbtn.setSelection(active);
		}
		toggleEditingMode(selection.isEditing());
	}

	private void toggleEditingMode(boolean isEditing) {
		vagonNameText.setEnabled(isEditing);
		compositionCombo.setEnabled(isEditing);
		isActiveChbtn.setEnabled(isEditing);
		revisionCorrectionTxt.setEnabled(isEditing);
		revisionDistanceTxt.setEnabled(isEditing);
		revisionOneEndDate.setEnabled(isEditing);
		revisionOneStartDate.setEnabled(isEditing);
		revisionTwoEndDate.setEnabled(isEditing);
		revisionTwoStartDate.setEnabled(isEditing);
		composite.setVisible(isEditing);
	}

	@Override
	public void addSelectionListener(ISelectionListener<VagonSelection> listner) {
		selectionListener = listner;
	}

	@Override
	public void removeSelectionListener(
			ISelectionListener<VagonSelection> listner) {
		selectionListener = null;
	}

}
